package org.rcy.framework.security.form;

import org.apache.commons.lang3.StringUtils;
import org.rcy.framework.api.security.SecurityUser;
import org.rcy.framework.security.authentication.authenticator.FormAuthenticator;
import org.rcy.framework.security.exception.UserNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class PasswordAuthenticator implements FormAuthenticator<PasswordToken> {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public PasswordAuthenticator() {
    }

    public void authenticate(PasswordToken originalToken, SecurityUser user) throws BadCredentialsException {
        if (!user.getEnabled()) {
            this.logger.warn("User Not Found:{}", user);
            throw new UserNotFoundException("User Not Found!");
        } else {
            String rawPassword = originalToken.getCredentials();
            String encodedPassword = user.getPassword();
            if (StringUtils.isBlank(encodedPassword) || !this.passwordEncoder.matches(rawPassword, encodedPassword)) {
                this.logger.warn("Authentication failed: password does not match stored value");
                throw new BadCredentialsException("Bad credentials:wrong password");
            }
        }
    }
}
